package xyz.kongbai121.demo.util;

import xyz.kongbai121.demo.domain.Comment;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class CommentUtil {

    public static List<Comment> commentLink(CopyOnWriteArrayList<Comment> commentList) {
        List<Comment> comments = new ArrayList<>();
        List<Comment> parents = new ArrayList<>();
        for (Comment comment : commentList) {
            if (comment.getCommentId() == null) {
                comments.add(comment);
                parents.add(comment);
            } else {
                for (Comment parent : parents) {
                    if (comment.getCommentId().equals(parent.getId())) {
                        if (parent.getComments() == null) {
                            parent.setComments(new ArrayList<Comment>());
                        }
                        parent.getComments().add(comment);
                        parents.add(comment);
                        //如果对list迭代过程中同时修改list，会报java.util.ConcurrentModificationException
                        // 的异常，所以我们需要break,当然break也可以提高算法效率
                        break;
                    }
                }
//                if (!foundParent) {
//                    throw new RuntimeException("can not find the parent comment");
//                }
            }
        }
        return comments;
    }

}